package com.demo.component.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LogInterceptor extends HandlerInterceptorAdapter {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private ThreadLocal<StopWatch> stopWatchThreadLocal = new ThreadLocal<>();

    /**
     * This implementation always returns {@code true}.
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //获取STOPWATCH并开始计时
        StopWatch stopWatch = stopWatchThreadLocal.get();
        if (stopWatch == null) {
            stopWatch = new StopWatch();
            stopWatchThreadLocal.set(stopWatch);
        }
        stopWatch.reset();
        stopWatch.start();
        //获取StringBuffer
        StringBuilder sb = new StringBuilder();
        String requestUrl = request.getRequestURI();
        if (logger.isDebugEnabled() && needLog(requestUrl)) {
            sb.append("request url: ").append(requestUrl).append(",").append("method: ").append(request.getMethod());
            if (StringUtils.isNotBlank(request.getQueryString())) {
                sb.append("     queryString: ").append(request.getQueryString());
            }
            logger.debug(sb.toString());
        }
        return true;
    }

    @Override
    public void postHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {
    }


    @Override
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        StopWatch stopWatch = stopWatchThreadLocal.get();
        if (stopWatch == null) {
            return;
        }
        stopWatch.stop();
        logger.debug("执行时间: {}s", stopWatch.getTime());

    }


    private boolean needLog(String requestUrl) {
        if (requestUrl.contains("chktomcat")) {
            return false;
        }
        return true;
    }

}
